﻿using UnityEngine;
using System.Collections;

public static class MethodExtension
{
    public static T GetOrAddComponentByPath<T>(this Transform tf, string path = "") where T : Component
    {
        Transform t;
        if (string.IsNullOrEmpty(path))
            t = tf;
        else
            t = tf.Find(path);

        if (null == t)
        {
            Debugger.LogError("没有查到" + path + "对应的Transform");
            return null;
        }

        T ret;
        ret = t.GetComponent<T>();
        if (null == ret)
            ret = t.gameObject.AddComponent<T>();
        return ret;
    }

    public static T GetOrAddComponentByPath<T>(this GameObject go, string path = "") where T : Component
    {
        return go.transform.GetOrAddComponentByPath<T>(path);
    }


    public static T GetComponentByPath<T>(this Transform tf, string path = "") where T : Component
    {
        Transform t;
        if (string.IsNullOrEmpty(path))
            t = tf;
        else
            t = tf.Find(path);

        if (null == t)
        {
            Debugger.LogError("没有查到" + path + "对应的Transform");
            return null;
        }

        T ret;
        ret = t.GetComponent<T>();
        if (null == ret)
        {
            Debugger.LogError("没有查到" + typeof(T).ToString() + "对应的Component");
            return null;
        }
        return ret;
    }

    public static T GetComponentByPath<T>(this GameObject go, string path = "") where T : Component
    {
        return go.transform.GetComponentByPath<T>(path);
    }
}
